package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;

import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void sendVerifyCode(String phone, String code) {
        /*   String key = "verify_code"+phone;*/
        String key = RedisKeys.VERIFY_CODE.join(phone);
        redisTemplate.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        //通过传入的key获取验证码的value值
        /*String key = "verify_code"+phone;*/
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String code = redisTemplate.opsForValue().get(key);
        return code;
    }

    @Override
    public String setToken(UserInfo userInfo) {
        //通过UUID生成唯一的token
        String token = UUID.randomUUID().toString().replace("-", "");
        String key = RedisKeys.USER_LOGIN.join(token);
        System.out.println(key);
        //设置到redis缓存中,JSON.toJSONString则是将对象转化为Json字符串。
        redisTemplate.opsForValue().set(key, JSON.toJSONString(userInfo), RedisKeys.USER_LOGIN.getTime(), TimeUnit.SECONDS);

        return token;
    }

    @Override
    public UserInfo getUserInfo(String token) {
        //先对token进行判断是否有值
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key = RedisKeys.USER_LOGIN.join(token);
        //判断redis缓存中是有有这个key
        if (redisTemplate.hasKey(key)) {
            String strUserinfo = redisTemplate.opsForValue().get(key);
            //将获取到的UserInfo字符串转为对象
            UserInfo userInfo = JSON.parseObject(strUserinfo, UserInfo.class);

            //重新设置token时间
            redisTemplate.opsForValue().set(token, JSON.toJSONString(userInfo), RedisKeys.USER_LOGIN.getTime(), TimeUnit.SECONDS);
            return userInfo;
        }
        return null;
    }
}
